<template>
	<uni-data-select v-model="fieldValue" :localdata="data" :clear="false" v-bind="$attrs"></uni-data-select>
</template>
<script setup>
	import {
		computed,
		unref,
		ref,
		watch
	} from 'vue'
	import _camelCase from 'lodash/camelCase';
	import Dict from '@/store/dict.js'
	import Com from '@/store/com.js'
	const store = {
		com: Com(),
		dict: Dict()
	}
	const emits = defineEmits(['update:modelValue']);
	/***
	 * 参数属性
	 * @property {Object[]} modelValue 默认值
	 * @property {list[]} list 下拉列表数据
	 * @property {Object} fillType 数据格式默认为{ label: 'dictLabel', value: 'dictValue' }
	 * @property {String} type store.dispatch的方法名
	 * @property {Boolean} original 是否保留原始数据，默认为false
	 */
	const props = defineProps({
		modelValue: {},
		list: {
			type: Array,
			default: () => [],
		},
		fileType: {
			type: Object,
			default: () => ({
				label: 'dictLabel',
				value: 'dictValue'
			}),
		},
		type: {
			type: String,
			default: '',
		},
		code: {
			type: String,
			default: '',
		},
	});
	let fieldValue = computed({
			get() {
				return props.modelValue;
			},
			set(val) {
				emits('update:modelValue', val);
			},
		}),
		dictType = computed(() => (props.type?.startsWith?.('GET') ? props.type : `GET${_camelCase(props.type)}`));
	let data = ref([])
	const initFn = () => {
		if (unref(dictType)) {
			(store.dict[unref(dictType)] || store.com[unref(dictType)])?.();
		} else {
			initialization();
		}
	}
	const initialization = (list = props.list) => {
		data.value = fileTypeFn(list);
	}
	/**
	 * 数据处理
	 * @param {[]} data 原始数据
	 * @param {} fileType 处理{ label: 'dictLabel', value: 'dictValue' }对象
	 */
	const fileTypeFn = (data, fileType = props.fileType) => {
		return data.map((val, i) => {
			const obj = {
				text: val[fileType.label],
				value: val[fileType.value],
			};
			if (props.original) {
				return {
					...obj,
					...val
				};
			} else {
				return obj;
			}
		});
	}
	const selectChange = (e) => {
		console.log(e);
	}
	// 监听数据变化
	watch(
		() => props.list,
		(val) => {
			if (val) initialization(val);
		}, {
			deep: true,
			immediate: true
		});
	watch(() => dictType.value,
		(val) => {
			initFn(val);
		}, {
			immediate: true
		})
	watch(
		() => store.dict[unref(dictType)?.replace('GET', '')] || store.com[unref(dictType)?.replace('GET', '')],
		(val) => {
			if (unref(dictType)) initialization(val);
		}, {
			deep: true,
			immediate: true
		});
</script>
<style>
</style>